<template>
  <div class="list-common-tab">
    <el-row :gutter="20">
      <el-col :span="18">
        <el-input
          v-model="search"
          placeholder="请输入检索内容"
          @keyup.enter="handleSearch"
          input-style="padding-right:30px"
        />
      </el-col>
      <el-col :span="6" class="operation-container">
        <el-button type="primary" @click="handleSearch">检索</el-button>
        <el-button type="info" @click="handleClear">清空</el-button>
        <el-button type="primary" @click="handleSelect">选择</el-button>
      </el-col>
    </el-row>
    <div class="star-table-container">
      <el-table
        :data="dataList"
        :stripe="stripe"
        :max-height="listHeight"
      >
        <el-table-column prop="targetName" label="角色名称" />
        <el-table-column prop="showOrder" label="排序" width="80"/>
        <el-table-column prop="op" align="center" label="操作" width="200">
          <template #default="scope">
            <el-button type="danger" @click="handleRemoveData(scope)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="star-table-pagination">
      <el-pagination
        background
        :total="listTotal"
        :layout="pageOperate"
        :default-page-size="size"
        :page-sizes="listPageSizes"
        v-model:page-size="pageSize"
        @size-change="handleSizeChange"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      draggable
      title=""
      destroy-on-close
      v-model="visibleForm"
      :close-on-click-modal="false"
      top="10vh"
    >
      <code-select :treeData="roleTreeData" :selected="selectedData" @close-dialog="closeDialog" @commit-selected="saveSelectedGrant" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import CodeSelect from '@/components/common/select/CodeSelect'
import { ref, onMounted, watch, computed } from 'vue'
import { stripe, size, pageOperate, listPageSizes } from '@/config/list'
import { loadGrantTargetList, deleteData, saveGrant, getSelectedGrant } from '@/api/system/privilege/GrantManager'
import { GrantType, GrantTargetType } from '@/model/system/privilege/GrantModel'
import { loadRoleTree } from '@/api/system/role/RoleManager'

import '@/style/list.less'

const search = ref('')
const dataList = ref([])
const listTotal = ref(0)
const pageSize = ref(size)
const currentPage = ref(1)
const visibleForm = ref(false)
const props = defineProps({ fid: String })
const roleTreeData = ref([])
const selectedData = ref([])

const listHeight = computed(() => {
  return 'calc(100vh - 355px)'
})

const handleSearch = () => {
  currentPage.value = 1
  loadListData()
}

const handleClear = () => {
  currentPage.value = 1
  search.value = ''
  loadListData()
}

const handleRemoveData = (scope) => {
  ElMessageBox.confirm('是否删除角色？')
    .then(() => {
      deleteData(scope.row.id).then(() => {
        ElMessage.success('删除成功！')
        reloadData()
      }).catch(error => {
        ElMessage.error(error.message)
      })
    })
    .catch(() => {
      // catch error
    })
}

const handleSelect = async () => {
  if (roleTreeData.value.length === 0) {
    await loadRoleTree().then(data => {
      roleTreeData.value = data
    })
  }
  getSelectedGrant(props.fid, GrantTargetType.Role).then(data => {
    selectedData.value = data.map(item => {
      return item.targetId
    })
    visibleForm.value = true
  })
}

const closeDialog = () => {
  visibleForm.value = false
}

const saveSelectedGrant = (roleList) => {
  const newArray = roleList.map((item, index) => {
    const grant = {
      sourceId: props.fid,
      fid: props.fid,
      sourceType: GrantType.Privilege,
      targetType: GrantTargetType.Role,
      targetId: item.value,
      targetName: item.label,
      showOrder: index + 1
    }
    return grant
  })

  saveGrant(props.fid, GrantTargetType.Role, newArray).then(() => {
    closeDialog()
    ElMessage.success('保存成功。')
    reloadData()
  }).catch((error) => {
    ElMessage.error(error.message || '保存失败，请联系管理员。')
  })
}

const reloadData = () => {
  loadListData()
}

const loadListData = () => {
  loadGrantTargetList({
    fid: props.fid,
    current: currentPage.value,
    pageSize: pageSize.value,
    search: search.value
  }, GrantTargetType.Role).then(data => {
    const { list, total } = data
    dataList.value = list
    listTotal.value = total
  })
}

const handleSizeChange = () => {
  loadListData()
}

const handleCurrentChange = () => {
  loadListData()
}

watch(
  () => props.fid,
  () => {
    currentPage.value = 1
    search.value = ''
    loadListData()
  }
)

onMounted(() => {
  loadListData()
})

</script>
